// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/home', redirect: '/dashboard' },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('../views/Register.vue')
  },
  {
    path: '/home',
    name: 'home',
    component: HomeView,
    children: [] // 动态路由会挂载到这里
  },

]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

router.beforeEach((to, from, next) => {
  const userStr = localStorage.getItem('user')
  const user = userStr ? JSON.parse(userStr) : null

  // 未登录不能访问其他页面
  if (!user && to.path !== '/login') {
    return next('/login')
  }

  // 登录用户访问没有权限的页面（你也可以在菜单返回结构中加入 roles 元信息来做判断）
  if (to.meta.roles && user && !to.meta.roles.includes(user.role)) {
    return next('/403')
  }

  next()
})

export default router
